/*
 * @Author: yang-tengyuyxd 1282291612@qq.com
 * @Date: 2024-10-31 11:11:38
 * @LastEditors: yang-tengyuyxd 1282291612@qq.com
 * @LastEditTime: 2024-10-31 13:17:11
 * @FilePath: /yxd/管道/命名管道/Server.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once
#include "Comm.hpp" //现在Server就可以看到公共路径下文件(管道文件)
#include<iostream>

class Init
{
public:
    Init()
    {
        umask(0);
        int n = ::mkfifo(gpipeFile.c_str(), gmode); // 创建管道文件
        if (n < 0)
        {
            std::cerr << "mkfifo error" << std::endl;
            return;
        }
        std::cout << "mkfifo success" << std::endl;

        // sleep(10);
    }
    ~Init()
    {
        int n = ::unlink(gpipeFile.c_str());
        if (n < 0)
        {
            std::cerr << "unlink error" << std::endl;
            return;
        }
        std::cout << "unlink success" << std::endl;
    }
};

Init init; // 把管道文件放Server.hpp

class Server
{
public:
    Server() : _fd(gdefultfd)
    {}
    bool OpenPipeForRead()
    {
       _fd=OpenPipe(gForRead);
       if(_fd<0)
       {
        return false;
       }
       return true;
    }
    // std::string *out     : 输出型参数
    // const std::string &  : 输入型参数
    // std::string &        : 输入输出型参数

    // 读管道
    int RevPipe(std::string *out)
    {
        char buffer[gsize];

        ssize_t n=::read(_fd,buffer,sizeof(buffer)-1);
        if(n>0)
        {
            buffer[n]=0;
            *out=buffer;
        }
        return n;
    }
    void ClosePipe()
    {
        ClosePipeHelper(_fd);
    }
    ~Server()
    {}

private:
    int _fd;
};